import React from 'react'
import { Button, Icon, Input, Table, Tag } from 'antd'
import Highlighter from 'react-highlight-words'
import { FormattedMessage } from 'react-intl'
import _ from 'lodash'

export default class TopicsStatusBox extends React.Component {
  state = {
    searchText: ''
  }

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
      <div style={{padding: 8}}>
        <Input
          ref={node => {
            this.searchInput = node
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{width: 188, marginBottom: 8, display: 'block'}}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{width: 90, marginRight: 8}}
        >
          Search
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{width: 90}}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{color: '#1890ff'}}/>
    ),
    onFilter: (value, record) => (record[dataIndex] || '')
      .toString()
      .toLowerCase()
      .includes(value.toLowerCase())
    ,
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select())
      }
    }
    ,
    render: text => (
      <Highlighter
        highlightStyle={{backgroundColor: '#ffc069', padding: 0}}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text.toString()}
      />
    ),
  })

  handleSearch = (selectedKeys, confirm) => {
    confirm()
    this.setState({searchText: selectedKeys[0]})
  }

  handleReset = clearFilters => {
    clearFilters()
    this.setState({searchText: ''})
  }

  formatTags = (item) => {
    if (!item) return ''

    const tagColors = item.split(',')
    return tagColors.map((item) => {
      const tagColor = item.split('|')
      return <Tag color={tagColor[1]}>{tagColor[0]}</Tag>
    })
  }
  getColumns = assignmentsFinishSpeedOverview => {
    let columns = [{
      title: <FormattedMessage id='姓名'/>,
      dataIndex: 'name'
    }, {
      title: <FormattedMessage id='tags'/>,
      dataIndex: 'tag',
      ...this.getColumnSearchProps('tag'),
      render: (item) => {
        return <span>{this.formatTags(item)}</span>
      }
    }]
    _.unionBy(assignmentsFinishSpeedOverview, 'topicId').forEach(item => {
      columns.push({
        title: <a onClick={()=>this.props.onChange(item.topicId)}>{item['主题']}</a>,
        dataIndex: item.topicId,
        render: (text) => {
          return <span>{this.formatDurationTime(text)}</span>
        }
      })
    })
    columns.push({
      title: '总时间',
      dataIndex: 'total',
      defaultSortOrder:'descend',
      sorter: (a, b) => {
        const aFinishCount = a.assignments.filter(item => !!item.startTimestamp && !!item.endTimestamp).length
        const bFinishCount = b.assignments.filter(item => !!item.startTimestamp && !!item.endTimestamp).length
        if (aFinishCount === bFinishCount) {
          return this.statisticTotalTime(b.assignments) - this.statisticTotalTime(a.assignments)
        }
        return bFinishCount - aFinishCount
      },
      render: (text, record) => {
        return this.formatDurationTime(record.assignments)
      }
    })
    return columns
  }

  formatDurationTime = assignmentsDuration => {
    const finishCount = assignmentsDuration.filter(item => !!item.startTimestamp && !!item.endTimestamp).length
    return <span>{finishCount}/{assignmentsDuration.length} | {this.formatTime(this.statisticTotalTime(assignmentsDuration))}</span>
  }

  statisticTotalTime = assignments => {
    return assignments.reduce((value, current) => {
      const {startTimestamp, endTimestamp} = current
      if (!startTimestamp || !endTimestamp) {
        return value
      }
      value += endTimestamp - startTimestamp
      return value
    }, 0)
  }
  formatTime = timestamp => {
    const hours = parseInt(timestamp / 60 / 60)
    const minutes = parseInt(timestamp / 60) - hours * 60

    return `${hours} H ${minutes} min`
  }
  getData = assignmentsQuizzesStatus => {
    const groupByNameAssignments = _.groupBy(assignmentsQuizzesStatus, 'name')
    return Object.keys(groupByNameAssignments).map(name => {
      const studentAssignments = groupByNameAssignments[name]
      let column = {name, tag: studentAssignments[0].tag, assignments: []}
      const groupByTopicAssignments = _.groupBy(studentAssignments, 'topicId')
      Object.keys(groupByTopicAssignments).forEach(topicId => {
        column[topicId] = groupByTopicAssignments[topicId]
        column.assignments.push(...groupByTopicAssignments[topicId])
      })
      return column
    })
  }

  render () {
    const {assignmentsFinishSpeedOverview} = this.props
    const columns = this.getColumns(assignmentsFinishSpeedOverview)
    const data = this.getData(assignmentsFinishSpeedOverview)

    return <Table columns={columns}
                  dataSource={data}
                  pagination={false}
                  bordered
                  size='small'
    />
  }
}
